package com.xydtech.ecard.merchant.service.impl;

import com.xydtech.common.annotation.DataScope;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.text.Convert;
import com.xydtech.common.utils.AESEncryptionUtils;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.custgroup.domain.EcardCustomerGroupMerchant;
import com.xydtech.ecard.custgroup.mapper.EcardCustomerGroupMerchantMapper;
import com.xydtech.ecard.merchant.domain.*;
import com.xydtech.ecard.merchant.mapper.EcardEnterpriseInfoMapper;
import com.xydtech.ecard.merchant.mapper.EcardMerchantHandoverMapper;
import com.xydtech.ecard.merchant.mapper.EcardMerchantReservationTaskMapper;
import com.xydtech.ecard.merchant.mapper.EcardMerchantTaskMapper;
import com.xydtech.ecard.merchant.service.IEcardEnterpriseInfoService;
import com.xydtech.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 电子名片企业信息Service业务层处理
 *
 * @author yuzhiguo
 * @date 2024-08-15 上午9:39
 */
@Service
public class EcardEnterpriseInfoServiceImpl implements IEcardEnterpriseInfoService {

    @Autowired
    private EcardEnterpriseInfoMapper ecardEnterpriseInfoMapper;
    @Autowired
    private EcardMerchantTaskMapper ecardMerchantTaskMapper;
    @Autowired
    private EcardMerchantReservationTaskMapper ecardMerchantReservationTaskMapper;
    @Autowired
    private EcardMerchantHandoverMapper ecardMerchantHandoverMapper;
    @Autowired
    private EcardCustomerGroupMerchantMapper ecardCustomerGroupMerchantMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询电子名片企业信息
     *
     * @param id 电子名片企业信息主键
     * @return 电子名片企业信息
     */
    @Override
    public EcardEnterpriseInfo selectEcardEnterpriseInfoById(Long id)
    {
        return ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoById(id);
    }

    /**
     * 查询电子名片企业信息列表
     *
     * @param ecardEnterpriseInfo 电子名片企业信息
     * @return 电子名片企业信息
     */
    @Override
    @DataScope(userAlias = "c", deptAlias = "b")
    public List<EcardEnterpriseInfo> selectEcardEnterpriseInfoList(EcardEnterpriseInfo ecardEnterpriseInfo, String salt)
    {
        List<EcardEnterpriseInfo> ecardEnterpriseInfoList = ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoList(ecardEnterpriseInfo);
        for (EcardEnterpriseInfo enterpriseInfo : ecardEnterpriseInfoList) {
            try {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(enterpriseInfo.getEntPhoneNumber())) {
                    enterpriseInfo.setEntPhoneNumber(AESEncryptionUtils.decrypt(enterpriseInfo.getEntPhoneNumber(), salt));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ecardEnterpriseInfoList;
    }

    /**
     * 新增电子名片企业信息
     *
     * @param ecardEnterpriseInfo 电子名片企业信息
     * @return 结果
     */
    @Override
    public int insertEcardEnterpriseInfo(EcardEnterpriseInfo ecardEnterpriseInfo)
    {
        return ecardEnterpriseInfoMapper.insertEcardEnterpriseInfo(ecardEnterpriseInfo);
    }

    /**
     * 修改电子名片企业信息
     *
     * @param ecardEnterpriseInfo 电子名片企业信息
     * @return 结果
     */
    @Override
    public int updateEcardEnterpriseInfo(EcardEnterpriseInfo ecardEnterpriseInfo)
    {
        return ecardEnterpriseInfoMapper.updateEcardEnterpriseInfo(ecardEnterpriseInfo);
    }

    /**
     * 批量删除电子名片企业信息
     *
     * @param ids 需要删除的电子名片企业信息主键
     * @return 结果
     */
    @Override
    public int deleteEcardEnterpriseInfoByIds(String ids)
    {
        return ecardEnterpriseInfoMapper.deleteEcardEnterpriseInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除电子名片企业信息信息
     *
     * @param id 电子名片企业信息主键
     * @return 结果
     */
    @Override
    public int deleteEcardEnterpriseInfoById(Long id)
    {
        return ecardEnterpriseInfoMapper.deleteEcardEnterpriseInfoById(id);
    }

    /**
     * 批量移交企业信息
     * @param ecardEnterpriseInfoList
     * @param registId
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int allocationEcardEnterpriseInfo(List<EcardEnterpriseInfo> ecardEnterpriseInfoList, Long registId, Long userId) {
        //转交记录
        List<EcardMerchantHandover> ecardMerchantHandoverList = new ArrayList<>();
        //待办任务
        List<EcardMerchantTask> ecardMerchantTaskList = new ArrayList<>();
        //待办预约任务
        List<EcardMerchantReservationTask> merchantReservationTaskList = new ArrayList<>();
        //行业客户信息
        List<EcardCustomerGroupMerchant> customerGroupMerchantList = new ArrayList<>();

        for(int i = 0; i < ecardEnterpriseInfoList.size(); i++){
            EcardEnterpriseInfo ecardEnterpriseInfo = ecardEnterpriseInfoList.get(i);
            //查询企业信息
            EcardEnterpriseInfo oldEcardEnterpriseInfo = ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoById(ecardEnterpriseInfo.getId());

            EcardMerchantHandover ecardMerchantHandover = new EcardMerchantHandover();
            ecardMerchantHandover.setMerchantId(ecardEnterpriseInfo.getId());
            ecardMerchantHandover.setTransferId(oldEcardEnterpriseInfo.getManagementPersonnelId());
            ecardMerchantHandover.setTransferDeptId(oldEcardEnterpriseInfo.getDeptId());
            ecardMerchantHandover.setRecipientId(ecardEnterpriseInfo.getManagementPersonnelId());
            ecardMerchantHandover.setRecipientDeptId(ecardEnterpriseInfo.getDeptId());
            ecardMerchantHandover.setMerchantType("3");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardMerchantHandoverList.add(ecardMerchantHandover);

            //查询拜访企业任务
            EcardMerchantTask ecardMerchantTask = new EcardMerchantTask();
            ecardMerchantTask.setMerchantId(ecardEnterpriseInfo.getId());
            ecardMerchantTask.setMerchantType("3");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardMerchantTask.setTaskSts(0);
            List<EcardMerchantTask> taskList = ecardMerchantTaskMapper.selectEcardMerchantTaskList(ecardMerchantTask);
            //待办任务，最多只有一条
            EcardMerchantTask newEcardMerchantTask = null;
            if(taskList.size() > 0) {
                EcardMerchantTask oldEcardMerchantTask = taskList.get(0);
                newEcardMerchantTask = new EcardMerchantTask();
                newEcardMerchantTask.setId(oldEcardMerchantTask.getId());
                newEcardMerchantTask.setCmRegistId(ecardEnterpriseInfo.getManagementPersonnelId());
                //待办任务list
                ecardMerchantTaskList.add(newEcardMerchantTask);
            }

            //查询未处理的企业预约任务
            List<EcardMerchantReservationTask> pendingMerchantReservationTaskList = ecardMerchantReservationTaskMapper.getMerchantReservationTaskByMerchantId(ecardEnterpriseInfo.getId(), "3");
            merchantReservationTaskList.addAll(pendingMerchantReservationTaskList);
            //查询行业客户信息
            EcardCustomerGroupMerchant customerGroupMerchant = ecardCustomerGroupMerchantMapper.selectEcardCustomerGroupMerchantByMerchantId(ecardEnterpriseInfo.getId(), "3");
            if (customerGroupMerchant != null) {
                EcardCustomerGroupMerchant groupMerchant = new EcardCustomerGroupMerchant();
                groupMerchant.setId(customerGroupMerchant.getId());
                groupMerchant.setManagementPersonnelId(ecardEnterpriseInfo.getManagementPersonnelId());
                groupMerchant.setDeptId(ecardEnterpriseInfo.getDeptId());
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ecardEnterpriseInfo.getDeptId());
                Long corpId = sysDept.getDeptId();//接收人的法人机构id
                groupMerchant.setCorpId(corpId);
                customerGroupMerchantList.add(groupMerchant);
            }
        }

        /**
         * 行业客户关联表同步批量转交20241204
         * 思路：
         * 1、先转交行业客户关联表中的信息，根据商户类型和商户id转交
         * 2、再转交对应商户信息
         */
        if(customerGroupMerchantList.size()>0) {
            //批量移交行业客户信息
            ecardCustomerGroupMerchantMapper.batchUpdateEcardGroupMerchantInfo(customerGroupMerchantList);
        }

        //批量移交企业
        int a = ecardEnterpriseInfoMapper.batchUpdateEcardEnterpriseInfo(ecardEnterpriseInfoList);
        //批量插入移交记录
        int b = ecardMerchantHandoverMapper.batchInsertEcardMerchantHandover(ecardMerchantHandoverList);

        if(ecardMerchantTaskList.size()>0) {
            //批量修改待办任务所属客户经理
            ecardMerchantTaskMapper.batchUpdateEcardMerchantTask(ecardMerchantTaskList);
        }

        if(merchantReservationTaskList.size()>0) {
            //循环设置新的移交人
            for(EcardMerchantReservationTask ecardMerchantReservationTask:merchantReservationTaskList){
                ecardMerchantReservationTask.setCmRegistId(registId);
            }
            //批量修改商户预约待办任务所属客户经理
            ecardMerchantReservationTaskMapper.batchUpdateEcardMerchantReservationTask(merchantReservationTaskList);
        }
        return a > b ? b:a;
    }

    /**
     * 批量释放企业
     * @param ecardEnterpriseInfoList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchReleaseEcardEnterpriseInfo(List<EcardEnterpriseInfo> ecardEnterpriseInfoList) {
        //待办任务
        List<EcardMerchantTask> ecardMerchantTaskList = new ArrayList<>();
        //待办预约任务
        List<EcardMerchantReservationTask> merchantReservationTaskList = new ArrayList<>();
        //行业客户信息
        List<EcardCustomerGroupMerchant> customerGroupMerchantList = new ArrayList<>();

        for(int i = 0; i < ecardEnterpriseInfoList.size(); i++){
            EcardEnterpriseInfo ecardEnterpriseInfo = ecardEnterpriseInfoList.get(i);
            //查询拜访企业任务
            EcardMerchantTask ecardMerchantTask = new EcardMerchantTask();
            ecardMerchantTask.setMerchantId(ecardEnterpriseInfo.getId());
            ecardMerchantTask.setMerchantType("3");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardMerchantTask.setTaskSts(0);
            List<EcardMerchantTask> taskList = ecardMerchantTaskMapper.selectEcardMerchantTaskList(ecardMerchantTask);
            //待办任务，最多只有一条
            EcardMerchantTask newEcardMerchantTask = null;
            if(taskList.size() > 0) {
                EcardMerchantTask oldEcardMerchantTask = taskList.get(0);
                newEcardMerchantTask = new EcardMerchantTask();
                newEcardMerchantTask.setId(oldEcardMerchantTask.getId());
                newEcardMerchantTask.setCmRegistId(ecardEnterpriseInfo.getManagementPersonnelId());
                //待办任务list
                ecardMerchantTaskList.add(newEcardMerchantTask);
            }

            //查询未处理的企业预约任务
            List<EcardMerchantReservationTask> pendingMerchantReservationTaskList = ecardMerchantReservationTaskMapper.getMerchantReservationTaskByMerchantId(ecardEnterpriseInfo.getId(), "3");
            merchantReservationTaskList.addAll(pendingMerchantReservationTaskList);
            //处理行业客户信息
            EcardCustomerGroupMerchant groupMerchant = new EcardCustomerGroupMerchant();
            groupMerchant.setMerchantId(ecardEnterpriseInfo.getId());
            groupMerchant.setMerchantType("3");//企业
            groupMerchant.setManagementPersonnelId(null);
            customerGroupMerchantList.add(groupMerchant);
        }

        //批量释放行业客户信息
        if (customerGroupMerchantList.size() > 0){
            ecardCustomerGroupMerchantMapper.batchReleaseEcardGroupMerchantInfo(customerGroupMerchantList);
        }

        //批量释放企业
        int i = ecardEnterpriseInfoMapper.batchReleaseEcardEnterpriseInfo(ecardEnterpriseInfoList);

        if(ecardMerchantTaskList.size()>0) {
            //批量修改待办任务所属客户经理
            ecardMerchantTaskMapper.batchUpdateEcardMerchantTask(ecardMerchantTaskList);
        }

        if(merchantReservationTaskList.size()>0) {
            //循环设置客户经理为null
            for(EcardMerchantReservationTask ecardMerchantReservationTask:merchantReservationTaskList){
                ecardMerchantReservationTask.setCmRegistId(null);
            }
            //批量修改商户预约待办任务所属客户经理
            ecardMerchantReservationTaskMapper.batchUpdateEcardMerchantReservationTask(merchantReservationTaskList);
        }
        return i;
    }

    /**
     * 批量启用/停用企业
     * @param ecardEnterpriseInfoList
     * @return
     */
    @Override
    public int batchSwitchOverEcardMerchantInfo(List<EcardEnterpriseInfo> ecardEnterpriseInfoList) {
        //行业客户信息
        List<EcardCustomerGroupMerchant> customerGroupMerchantList = new ArrayList<>();
        for(int i = 0; i < ecardEnterpriseInfoList.size(); i++){
            EcardEnterpriseInfo ecardEnterpriseInfo = ecardEnterpriseInfoList.get(i);
            //处理行业客户信息
            EcardCustomerGroupMerchant groupMerchant = new EcardCustomerGroupMerchant();
            groupMerchant.setMerchantId(ecardEnterpriseInfo.getId());
            groupMerchant.setMerchantType("3");//企业
            groupMerchant.setState(ecardEnterpriseInfo.getState());
            customerGroupMerchantList.add(groupMerchant);
        }
        //批量启/停用行业客户信息
        if (customerGroupMerchantList.size() > 0){
            ecardCustomerGroupMerchantMapper.batchSwitchOverEcardGroupMerchantInfo(customerGroupMerchantList);
        }
        return ecardEnterpriseInfoMapper.batchSwitchOverEcardMerchantInfo(ecardEnterpriseInfoList);
    }

    /**
     * 查询导出的企业信息
     * @param ecardEnterpriseInfo
     * @return
     */
    @Override
    @DataScope(userAlias = "c", deptAlias = "b")
    public List<EcardEnterpriseInfo> selectEcardEnterpriseInfoListByExport(EcardEnterpriseInfo ecardEnterpriseInfo, String salt) {
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ShiroUtils.getSysUser().getDeptId());
        ecardEnterpriseInfo.setDictDeptId(sysDept.getDeptId());
        List<EcardEnterpriseInfo> ecardEnterpriseInfoList = ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoListByExport(ecardEnterpriseInfo);
        for (EcardEnterpriseInfo enterpriseInfo : ecardEnterpriseInfoList) {
            try {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(enterpriseInfo.getEntPhoneNumber())) {
                    enterpriseInfo.setEntPhoneNumber(AESEncryptionUtils.decrypt(enterpriseInfo.getEntPhoneNumber(), salt));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ecardEnterpriseInfoList;
    }

    /**
     * 根据id集合查询企业信息
     * @param ids
     * @return
     */
    @Override
    public List<EcardEnterpriseInfo> selectEcardEnterpriseInfoByIds(String ids, String salt) {
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ShiroUtils.getSysUser().getDeptId());
        List<EcardEnterpriseInfo> ecardEnterpriseInfoList = ecardEnterpriseInfoMapper.selectEcardEnterpriseInfoByIds(Convert.toStrArray(ids), sysDept.getDeptId());
        for (EcardEnterpriseInfo enterpriseInfo : ecardEnterpriseInfoList) {
            try {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(enterpriseInfo.getEntPhoneNumber())) {
                    enterpriseInfo.setEntPhoneNumber(AESEncryptionUtils.decrypt(enterpriseInfo.getEntPhoneNumber(), salt));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ecardEnterpriseInfoList;
    }
}
